<!-- frontend/src/components/VideoPanel.vue -->
<template>
  <div class="video-panel">
    <div class="video-panel-header">
      <h3>🎬 视频内容分析工作台</h3>
    </div>
    
    <!-- 主内容区 -->
    <div class="video-content">
      <!-- 输入侧边栏 -->
      <div class="input-sidebar">
        <div class="video-upload-section">
          <h4>📹 上传视频文件</h4>
          <div class="upload-area" :class="{ 'drag-over': dragOver }" 
               @drop="handleDrop" 
               @dragover.prevent="dragOver = true"
               @dragleave="dragOver = false"
               @click="triggerFileInput">
            <input ref="fileInput" type="file" accept="video/*" @change="handleFileSelect" style="display: none;">
            <div v-if="!selectedVideo" class="upload-placeholder">
              <div class="upload-icon">🎬</div>
              <p>点击或拖拽上传视频文件</p>
              <p class="upload-hint">支持 MP4, AVI, MOV 等格式</p>
            </div>
            <div v-else class="video-preview">
              <video :src="videoPreviewUrl" controls class="preview-video"></video>
              <div class="video-info">
                <p>{{ selectedVideo.name }}</p>
                <p>{{ formatFileSize(selectedVideo.size) }}</p>
              </div>
              <button class="remove-video" @click.stop="removeVideo">✕</button>
            </div>
          </div>
        </div>
        
        
        
        <!-- 文本指令输入 -->
        <div class="analysis-input">
          <label>输入文字</label>
          <textarea v-model="inputText" rows="3" 
                    @keypress="handleKeyPress"
                    :placeholder="chatHistory.length > 0 ? '继续提问...(Enter发送, Shift+Enter换行)' : '请输入您的问题或指令...(Enter发送, Shift+Enter换行)'"></textarea>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn primary analyze-btn" 
                  @click="startAnalysis" 
                  :disabled="!selectedVideo || analyzing">
            {{ analyzing ? '分析中...' : (chatHistory.length > 0 ? '继续对话' : '开始分析') }}
          </button>
          <button class="btn secondary" @click="clearConversation" v-if="chatHistory.length > 0">
            清空对话
          </button>
        </div>
        
        <!-- 对话统计 -->
        <div class="conversation-stats" v-if="chatHistory.length > 0">
          <p class="stats-info">💬 对话轮次: {{ Math.floor(chatHistory.length / 2) }}</p>
          <p class="stats-hint">💡 提示: 可以继续提问，AI会记住上下文</p>
        </div>
      </div>

      <!-- 聊天主界面 -->
      <div class="chat-main">
        <div class="chatbot-container" ref="videoChatContainer">
          <div v-if="chatHistory.length === 0" class="no-messages">
            <p>请上传视频文件并开始分析</p>
          </div>
          <div v-else class="chat-messages">
            <div v-for="(message, index) in chatHistory" :key="index" 
                 class="message-item"
                 :class="{
                   'user-message': message.role === '用户',
                   'ai-message': message.role === 'AI',
                   'system-message': message.role === '系统'
                 }">
              <div class="message-header">
                <span class="message-role">
                  {{ message.role === '用户' ? '👤 用户' : message.role === 'AI' ? '🤖 AI助手' : '⚙️ 系统' }}
                </span>
                <span class="message-time">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-content" v-html="renderMarkdown(message.content)"></div>
            </div>
          </div>
          <div v-if="analyzing" class="analyzing-indicator">
            <div class="spinner"></div>
            <span>AI正在分析视频内容，请稍候...</span>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { API_BASE_URL } from '@/config/api';

// 响应式数据
const selectedVideo = ref<File | null>(null);
const videoPreviewUrl = ref<string>('');
const inputText = ref('');
const analyzing = ref(false);
const chatHistory = ref<any[]>([]);
const dragOver = ref(false);
const fileInput = ref<HTMLInputElement>();

// 文件上传相关方法
const triggerFileInput = () => {
  fileInput.value?.click();
};

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    setSelectedVideo(file);
  }
};

const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  dragOver.value = false;
  const file = event.dataTransfer?.files[0];
  if (file && file.type.startsWith('video/')) {
    setSelectedVideo(file);
  }
};

const setSelectedVideo = (file: File) => {
  selectedVideo.value = file;
  const reader = new FileReader();
  reader.onload = (e) => {
    videoPreviewUrl.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);
};

const removeVideo = () => {
  selectedVideo.value = null;
  videoPreviewUrl.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

// 工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

const renderMarkdown = (content: string) => {
  // 简单的markdown渲染
  return content
    .replace(/## (.*)/g, '<h2>$1</h2>')
    .replace(/### (.*)/g, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/- (.*)/g, '<li>$1</li>')
    .replace(/\n/g, '<br>')
    .replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
};

// 分析功能 - 支持多轮对话
const startAnalysis = async () => {
  if (!selectedVideo.value) return;
  
  // 如果没有输入文本，提示用户
  if (!inputText.value || !inputText.value.trim()) {
    alert('请输入问题或指令');
    return;
  }
  
  analyzing.value = true;
  
  try {
    // 准备对话历史（只发送用户和AI的对话，不包括系统消息）
    const historyForApi = chatHistory.value
      .filter(msg => msg.role === '用户' || msg.role === 'AI')
      .map(msg => ({
        role: msg.role === '用户' ? 'user' : 'assistant',
        content: msg.content
      }));
    
    // 调用分析API
    const formData = new FormData();
    formData.append('video', selectedVideo.value);
    formData.append('input_text', inputText.value);
    formData.append('chat_history', JSON.stringify(historyForApi));  // 发送对话历史
    
    console.log(`发送对话历史: ${historyForApi.length} 条`);
    
    const response = await fetch(`${API_BASE_URL}/api/video/analyze-complete`, {
      method: 'POST',
      body: formData
    });
    
    if (response.ok) {
      const result = await response.json();
      
      // 添加用户输入到聊天历史
      chatHistory.value.push({
        role: '用户',
        content: inputText.value,
        timestamp: new Date().toISOString()
      });
      
      // 添加AI回复到聊天历史
      chatHistory.value.push({
        role: 'AI',
        content: result.analysis_result || result.error || '分析完成',
        timestamp: new Date().toISOString()
      });
      console.log('chatHistory', chatHistory.value);
      // 清空输入
      inputText.value = '';
      
      // 滚动到底部显示新消息
      setTimeout(scrollToVideoChatBottom, 100);
      
    } else {
      const errorMsg = '分析失败，请检查网络连接或稍后重试';
      chatHistory.value.push({
        role: '系统',
        content: errorMsg,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    console.error('分析请求失败:', error);
    chatHistory.value.push({
      role: '系统',
      content: '分析请求失败，请检查网络连接',
      timestamp: new Date().toISOString()
    });
  } finally {
    analyzing.value = false;
  }
};

const clearConversation = () => {
  if (confirm('确定要清空所有对话记录吗？')) {
    chatHistory.value = [];
    inputText.value = '';
  }
};

// 自动滚动到视频对话底部
const scrollToVideoChatBottom = () => {
  const container = document.querySelector('.chatbot-container');
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
};

// 支持回车键发送消息
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    startAnalysis();
  }
};
</script>

<style scoped>
.video-panel {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.video-panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
  background: white;
}

.video-panel-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.video-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  height: calc(100vh - 60px);
  width: 100%;
  box-sizing: border-box;
}

.input-sidebar {
  width: 350px;
  padding: 20px;
  background: white;
  border-right: 1px solid #e2e8f0;
  overflow-y: auto;
  height: 100%;
  flex-shrink: 0;
  box-sizing: border-box;
}

.video-upload-section h4 {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 13px;
  font-weight: 600;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.upload-area:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}

.upload-area.drag-over {
  border-color: #3b82f6;
  background: #eff6ff;
}

.upload-placeholder {
  color: #6b7280;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 4px;
}

.video-preview {
  position: relative;
}

.preview-video {
  width: 100%;
  max-height: 140px;
  border-radius: 8px;
  object-fit: cover;
}

.video-info {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
}

.remove-video {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.advanced-params {
  margin-top: 12px;
  padding: 10px;
  background: #f8fafc;
  border-radius: 8px;
}

.advanced-params h5 {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 13px;
  font-weight: 600;
}

.param-row {
  margin-bottom: 4px;
}

.param-row label {
  display: block;
  margin-bottom: 4px;
  font-size: 12px;
  color: #6b7280;
}

.slider {
  width: 100%;
  height: 2px;
  border-radius: 2px;
  background: #e2e8f0;
  outline: none;
  -webkit-appearance: none;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #3b82f6;
  cursor: pointer;
}

.select-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  font-size: 14px;
}

.analysis-input {
  margin-top: 24px;
  width: 100%;
}

.analysis-input label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.analysis-input textarea {
  width: 100%;
  padding: 16px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  resize: vertical;
  font-family: inherit;
  font-size: 15px;
  min-height: 100px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 8px;
}

.btn {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.primary {
  background: #3b82f6;
  color: white;
}

.btn.primary:hover:not(:disabled) {
  background: #2563eb;
}

.btn.primary:disabled {
  background: #9ca3af;
  cursor: not-allowed;
}

.btn.secondary {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn.secondary:hover:not(:disabled) {
  background: #e5e7eb;
}

.conversation-stats {
  margin-top: 20px;
  padding: 12px;
  background: #f0f9ff;
  border-left: 3px solid #3b82f6;
  border-radius: 6px;
}

.stats-info {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #1e40af;
  font-weight: 600;
}

.stats-hint {
  margin: 0;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  height: 100%;
  width: calc(100% - 350px);
  box-sizing: border-box;
  overflow: hidden;
}

.chatbot-container {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.no-messages {
  text-align: center;
  color: #6b7280;
  margin-top: 50px;
}

.chat-messages {
    /* 移除非标准的space-y属性 */
  }

  .message-item {
    margin-bottom: 12px;
    padding: 16px 18px;   /* 增加内边距 */
    border-radius: 8px;
    transition: all 0.2s ease;
    min-height: 60px;
  }

.message-item.user-message {
  background: #eff6ff;
  border-left: 3px solid #3b82f6;
}

.message-item.ai-message {
  background: #f0fdf4;
  border-left: 3px solid #10b981;
}

.message-item.system-message {
  background: #fef3c7;
  border-left: 3px solid #f59e0b;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #6b7280;
}

.message-role {
  font-weight: 600;
  color: #374151;
}

.message-content {
  line-height: 1.7;
  color: #374151;
  font-size: 15px;
}

.message-content h2,
.message-content h3 {
  margin-top: 12px;
  margin-bottom: 8px;
  color: #1e293b;
}

.message-content ul {
  margin: 8px 0;
  padding-left: 20px;
}

.message-content li {
  margin-bottom: 4px;
}

.analyzing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #eff6ff;
  border-radius: 8px;
  color: #1e40af;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

</style>
